﻿using Coldairarrow.Business.PB;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.PB
{
    [Route("/PB/[controller]/[action]")]
    public class PB_ProcecureSubPriceController : BaseApiController
    {
        #region DI

        readonly IOperator _operator;
        public PB_ProcecureSubPriceController(IPB_ProcecureSubPriceBusiness pB_ProcecureSubPriceBus, IOperator @operator)
        {
            _pB_ProcecureSubPriceBus = pB_ProcecureSubPriceBus;
            _operator = @operator;
        }
      
        IPB_ProcecureSubPriceBusiness _pB_ProcecureSubPriceBus { get; }

        #endregion

        #region 获取

        /// <summary>
        /// 查询工序单价
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageResult<ProcecureSubPriceDTO>> GetDataList(PageInput<SubPriceConditionDTO> input)
        {
            return await _pB_ProcecureSubPriceBus.GetDataListAsync(input);
        }

        [HttpPost]
        public async Task<PB_ProcecureSubPrice> GetTheData(IdInputDTO input)
        {
            return await _pB_ProcecureSubPriceBus.GetTheDataAsync(input.id);
        }

        /// <summary>
        /// 添加时间段的工序价格
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task InsertSubPrice(SubPriceDTO data)
        {
            await _pB_ProcecureSubPriceBus.InsertSubPriceAsync(data);
        }

        /// <summary>
        /// 价格导入模板
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoCheckJWT]
        public IActionResult ExportToExcel()
        {
            HSSFWorkbook book = new HSSFWorkbook();
            ISheet sheet = book.CreateSheet("价格导入模板");
            //创建excel 表头
            IRow header = sheet.CreateRow(0);

            ICell cell = header.CreateCell(0);
            cell.SetCellValue("物料编码");

            cell = header.CreateCell(1);
            cell.SetCellValue("工序全称");

           

            cell = header.CreateCell(2);
            cell.SetCellValue("单价");

            cell = header.CreateCell(3);
            cell.SetCellValue("计价方式");



            //输出的文件名称
            string fileName = "价格导入模板" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + ".xls";
            //把Excel转为流，输出
            //创建文件流
            System.IO.MemoryStream bookStream = new System.IO.MemoryStream();
            //将工作薄写入文件流
            book.Write(bookStream);

            //输出之前调用Seek（偏移量，游标位置) 把0位置指定为开始位置
            bookStream.Seek(0, System.IO.SeekOrigin.Begin);
            //Stream对象,文件类型,文件名称
            return File(bookStream, "application/vnd.ms-excel", fileName);

        }
        /// <summary>
        /// 价格表导入
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="StartDate">开始日日期</param>
        /// <param name="EndDate">结束日期</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<AjaxResult> Import(IFormFile file,string StartDate,string EndDate) {
            string ReturnValue = string.Empty;
            //起始时间 截止时间
            int days = (Convert.ToDateTime(EndDate) - Convert.ToDateTime(StartDate)).Days + 1;
            //定义一个bool类型的变量用来做验证
            bool flag = true;
            try
            {
                #region 检查文件
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                //定义一个集合一会儿将数据存储进来,全部一次丢到数据库中保存
                var Data = new List<PB_MaterialPrice>();
 
                List<string> liststr = new List<string>();
                MemoryStream ms = new MemoryStream();
                file.CopyTo(ms);
                ms.Seek(0, SeekOrigin.Begin);
                IWorkbook book;
                if (fileExt == ".xlsx")
                {
                    book = new XSSFWorkbook(ms);
                }
                else if (fileExt == ".xls")
                {
                    book = new HSSFWorkbook(ms);
                }
                else
                {
                    book = null;
                }
                ISheet sheet = book.GetSheetAt(0);

                int CountRow = sheet.LastRowNum+1 ;//获取总行数

                if (CountRow - 1 == 0)
                {
                    return Error("Excel列表数据项为空!");

                }
                #endregion
                #region 循环验证
                for (int i = 1; i < CountRow; i++)
                {
                    //获取第i行的数据
                    var row = sheet.GetRow(i);
                    if (row != null)
                    {
                        //循环的验证单元格中的数据
                        for (int j = 0; j < 6; j++)
                        {
                            if ((j == 4 || j == 5) || (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0))
                            {
                                //return Error(ReturnValue += $"注意第{i + 1}行,第{j + 1}列数据为空。");
                            }
                            else
                            if (row.GetCell(j) == null || row.GetCell(j).ToString().Trim().Length == 0)
                            {
                                flag = false;
                                return Error(ReturnValue += $"第{i + 1}行,第{j + 1}列数据不能为空。");
                            }
                        }
                    }
                }
                #endregion
                if (flag)
                {

                    for (int i = 0; i < CountRow; i++)
                    {
                        if (i != 0)
                        {
                            for (int day=0;day<days;day++) {

                                PB_MaterialPrice pB_MaterialPrice = new PB_MaterialPrice();
                                var row = sheet.GetRow(i);
                                if (row.GetCell(0) != null && row.GetCell(0).ToString().Trim().Length > 0)
                                {
                                    pB_MaterialPrice.Id = IdHelper.GetId();
                                    pB_MaterialPrice.CreatorId = _operator.UserId;
                                    pB_MaterialPrice.CreateTime = DateTime.Now;
                                    pB_MaterialPrice.CreatorRealName = _operator.UserName;
                                    pB_MaterialPrice.Deleted = false;
                                    pB_MaterialPrice.Materialid = row.GetCell(0).ToString();
                                    pB_MaterialPrice.Deptid = _operator.Property.DepartmentId;
                                    pB_MaterialPrice.WorkDate = Convert.ToDateTime(StartDate).AddDays(day) ;
                                }
                                if (row.GetCell(1) != null && row.GetCell(1).ToString().Trim().Length > 0)
                                {
                                    pB_MaterialPrice.ProcecureSubid = row.GetCell(1).ToString();
                                }
                                if (row.GetCell(2) != null && row.GetCell(2).ToString().Trim().Length > 0)
                                {
                                    pB_MaterialPrice.UnitPrice = Convert.ToDouble(row.GetCell(2).ToString());
                                }
                                else
                                {
                                    return Error("请输入单价");
                                }
                                if (row.GetCell(3) != null && row.GetCell(3).ToString().Trim().Length > 0)
                                {
                                    pB_MaterialPrice.PricingMethod = row.GetCell(3).ToString() == "数量" ? false : true;
                                }
                                else {
                                    return Error("请输入数量或重量");
                                }
                                Data.Add(pB_MaterialPrice);
                            }
   
                        }

                    }            
                    //项目管理
                    var listContactsId = Data.Select(s => s.Materialid).Select(s => s.Trim()).Distinct().ToList();
                    var ProjectId = _pB_ProcecureSubPriceBus.GetQueryable<PB_Material>().Where(w => listContactsId.Contains(w.Code)).ToDictionary(k => k.Id, v => v.Code);
                    var PB_ProcecureSub = Data.Select(s => s.ProcecureSubid).Select(s => s.Trim()).Distinct().ToList();
                    var PB_ProcecureSubId = _pB_ProcecureSubPriceBus.GetQueryable<PB_ProcecureSub>().Where(w => PB_ProcecureSub.Contains(w.Name)).ToDictionary(k => k.Id, v => v.Name);
                    foreach (var item in Data)
                    {
                        var Code = item.Materialid;
                        var ProsubCode = item.ProcecureSubid;
                        item.Materialid = ProjectId.FirstOrDefault(w => w.Value.Contains(item.Materialid.Trim())).Key;
                           item.ProcecureSubid = PB_ProcecureSubId.FirstOrDefault(w => w.Value.Contains(item.ProcecureSubid.Trim())).Key;
                        var db = _pB_ProcecureSubPriceBus.GetQueryable<PB_Material>().Where(m=>m.Id==item.Materialid).FirstOrDefault();
                        var dd = _pB_ProcecureSubPriceBus.GetQueryable<PB_ProcecureSub>().Where(m => m.Id == item.ProcecureSubid).FirstOrDefault();
                        if (db==null) {
                            
                            return Error("物料编号不存在:" + Code);
                        }
                        if (dd==null) {
                            return Error("工序编号不存在:" + ProsubCode);
                           
                        }
                        var count = _pB_ProcecureSubPriceBus.GetQueryable<PB_MaterialPrice>().Where(m=>m.Materialid==item.Materialid&&m.ProcecureSubid==item.ProcecureSubid&&m.WorkDate==item.WorkDate).FirstOrDefault();
                        if (count!=null) {

                            return Error("重复添加:物料编号" + Code+ "工序"+ProsubCode);
                        }

                    }
                    if (Data.Count > 0)
                    {
                            await _pB_ProcecureSubPriceBus.AddDataExlAsync(Data);
                       
                       
                        ReturnValue = $"数据导入成功,共导入{CountRow - 1}条数据。";
                    }
                }
                if (!flag)
                {
                    return Error(ReturnValue = "数据存在问题！" + ReturnValue);
                }
            }

            catch (Exception EX)
            {
                ReturnValue = EX.ToString();
                return Error(ReturnValue);
            }
            return Success(ReturnValue);
        }
        #endregion

        #region 提交

        [HttpPost]
        public async Task SaveData(PB_ProcecureSubPrice data)
        {
            if (data.Id.IsNullOrEmpty())
            {
                InitEntity(data);

                await _pB_ProcecureSubPriceBus.AddDataAsync(data);
            }
            else
            {
                await _pB_ProcecureSubPriceBus.UpdateDataAsync(data);
            }
        }

        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _pB_ProcecureSubPriceBus.DeleteDataAsync(ids);
        }


        #endregion
    }
}